package com.tongguan.paypos.activity.trans;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.Button;
import android.widget.TextView;

import com.tongguan.paypos.R;
import com.tongguan.paypos.base.BaseActivity;
import com.tongguan.paypos.base.MyApplication;
import com.tongguan.paypos.common.AppConstants;
import com.tongguan.paypos.common.RequestCallback;
import com.tongguan.paypos.common.UrlConstants;
import com.tongguan.paypos.common.User;
import com.tongguan.paypos.entity.CreateOrderInfo;
import com.tongguan.paypos.entity.PayType;
import com.tongguan.paypos.entity.PayTypeInfo;
import com.tongguan.paypos.entity.TransUnionInfo;
import com.tongguan.paypos.utils.AppUtils;
import com.tongguan.paypos.utils.Arith;
import com.tongguan.paypos.utils.L;
import com.tongguan.paypos.utils.NumberUtils;
import com.tongguan.paypos.utils.ToastUtils;
import com.tongguan.paypos.utils.Utils;

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MoneyInputActivity extends BaseActivity {
    private static final int REQUEST_CODE_POS = 11000;
    public static final String DEFAULT_INPUT = "default_input";

    @BindView(R.id.txt_integer)
    TextView mTxtInteger;
    @BindView(R.id.txt_decimal)
    TextView mTxtDecimal;
    @BindView(R.id.btn_1)
    Button mBtn1;
    @BindView(R.id.btn_2)
    Button mBtn2;
    @BindView(R.id.btn_3)
    Button mBtn3;
    @BindView(R.id.btn_cancel)
    Button mBtnCancel;
    @BindView(R.id.btn_4)
    Button mBtn4;
    @BindView(R.id.btn_5)
    Button mBtn5;
    @BindView(R.id.btn_6)
    Button mBtn6;
    @BindView(R.id.btn_backspace)
    Button mBtnBackspace;
    @BindView(R.id.btn_7)
    Button mBtn7;
    @BindView(R.id.btn_8)
    Button mBtn8;
    @BindView(R.id.btn_9)
    Button mBtn9;
    @BindView(R.id.btn_0)
    Button mBtn0;
    @BindView(R.id.btn_enter)
    Button mBtnEnter;

    private StringBuffer total;
    private String stateInput = "0";//默认 “0”

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_money_input);
        ButterKnife.bind(this);
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            stateInput = extras.getString(DEFAULT_INPUT, "0");
            if ("0".equals(stateInput) || "1".equals(stateInput)) {
                initTile(R.string.title_money_input, true);
                initPayType();
            } else if ("2".equals(stateInput)) {
                initTile(R.string.title_money_trans, true);
            }
        }
        total = new StringBuffer();
        initEvent();
    }

    private void initEvent() {
        mBtn0.setOnClickListener(v -> count("0"));
        mBtn1.setOnClickListener(v -> count("1"));
        mBtn2.setOnClickListener(v -> count("2"));
        mBtn3.setOnClickListener(v -> count("3"));
        mBtn4.setOnClickListener(v -> count("4"));
        mBtn5.setOnClickListener(v -> count("5"));
        mBtn6.setOnClickListener(v -> count("6"));
        mBtn7.setOnClickListener(v -> count("7"));
        mBtn8.setOnClickListener(v -> count("8"));
        mBtn9.setOnClickListener(v -> count("9"));
        mBtnCancel.setOnClickListener(v -> finish());
        mBtnBackspace.setOnClickListener(v -> {
            int length = total.length();
            if (length != 0) {
                total.deleteCharAt(length - 1);
                changeContent();
            }
        });
        mBtnBackspace.setOnLongClickListener(v -> {
            mTxtInteger.setText(R.string.money_unit_1);
            mTxtDecimal.setText(R.string.money_unit_3);
            total.delete(0, total.length());
            return true;
        });

        mBtnEnter.setOnClickListener(v -> {
            String money = total.toString(); //单位分
            if (TextUtils.isEmpty(money)) {
                ToastUtils.showCustom(context, "请输入消费金额");
                return;
            }
            Double valueOfMoney = Arith.div(Double.parseDouble(money), 100);//高精度计算
            if (valueOfMoney < AppConstants.MONEY_LIMIT_PAY) {//额度限制
                ToastUtils.showCustom(context, "最低消费金额限制：" + AppConstants.MONEY_LIMIT_PAY + "元");
                return;
            }
            L.d("total = " + money + " 金额 = " + valueOfMoney);
            // 获取订单
            if ("0".equals(stateInput)) {
                getOrder(valueOfMoney);
            } else if ("1".equals(stateInput)) {
                Bundle bundle = new Bundle();
                bundle.putDouble(PayTypeSelectActivity.MONEY, valueOfMoney);
                jumpAct(QRCodesPay.class, bundle, false, true);
            } else if ("2".equals(stateInput)) {
                Bundle bundle = new Bundle();
                bundle.putString("amount",NumberUtils.getDoubleFormat(valueOfMoney));
                AppUtils.runComponent(MoneyInputActivity.this, AppConstants.UNION_PAY_APP_PACKAGE, AppConstants.SALE_DIR, bundle, REQUEST_CODE_POS);
            } else {
                ToastUtils.showCustom(context, "跳转状态错误");
            }
        });
    }


    private void count(String params) {
        if (total.length() > 8) {
            return;
        }
        total.append(params);
        changeContent();
    }

    private void changeContent() {
        int length = total.length();
        if (length < 3) {
            if (length < 2) {
                String temp = "0" + total.toString();
                mTxtDecimal.setText(temp);
                if (length == 0) {
                    mTxtDecimal.setText(R.string.money_unit_3);
                }
            } else {
                mTxtDecimal.setText(total.toString());
            }
            mTxtInteger.setText(R.string.money_unit_1);
        } else {
            NumberFormat format = NumberFormat.getNumberInstance();
            mTxtInteger.setText(format.format(Double.parseDouble(total.substring(0, length - 2))));
            mTxtDecimal.setText(total.subSequence(length - 2, length));
        }
    }

    private void getOrder(double money) {
        params = new HashMap<>();
        params.put(UrlConstants.KEY_ACCOUNT, User.getInstance().getAccount());
        params.put(UrlConstants.KEY_PAY_MONEY, String.valueOf(money));//单位元
        RequestCallback.post(context, UrlConstants.CREATE_ORDER, params, mDialog, new AbstractRequestCallback() {
            @Override
            public void onResponse(String response, int id) {
                CreateOrderInfo createOrder = CreateOrderInfo.objectFromData(response);
                if (createOrder.getStatus() != 100) {
                    ToastUtils.showCustom(context, createOrder.getMessage());
                    return;
                }
                Bundle bundle = new Bundle();
                bundle.putDouble(PayTypeSelectActivity.MONEY, money);
                bundle.putString(PayTypeSelectActivity.ORDER_ID, createOrder.getOrderId());
                jumpAct(PayTypeSelectActivity.class, bundle, false, true);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        L.d("requestCode = " + requestCode + " resultCode = " + resultCode);
        //银联
        if (requestCode == REQUEST_CODE_POS) {
            if (resultCode == RESULT_OK) {
                String result = data.getStringExtra("result");
                String message = Utils.assembleTransUnionInfo(result, true);
                L.d(message);
                finish();
            } else {
                ToastUtils.showCustom(context, "支付取消或失败");
            }
        }
    }

    /**
     * 加载支付方式
     */
    private void initPayType() {
        if (MyApplication.getInstance().getPayTypes() == null) {
            params = new HashMap<>();
            params.put(UrlConstants.KEY_ACCOUNT, User.getInstance().getAccount());
            RequestCallback.post(context, UrlConstants.GET_PAY_TYPE, params, new AbstractRequestCallback() {
                @Override
                public void onResponse(String response, int id) {
                    PayTypeInfo payTypeInfo = PayTypeInfo.objectFromData(response);
                    if (payTypeInfo.getStatus() != 100) {
                        ToastUtils.showCustom(context, payTypeInfo.getMessage());
                        return;
                    }
                    List<PayTypeInfo.PayTypesBean> payTypes = payTypeInfo.getPayTypes();
                    if (payTypes == null || payTypes.size() == 0) {
                        return;
                    }
                    ArrayList<PayType> mPayTypes = new ArrayList<>();
                    //固定支付方式
                    for (PayTypeInfo.PayTypesBean payType : payTypes) {
                        PayType data = AppConstants.payTypeMap.get(payType.getType());
                        if (data == null){
                            continue;
                        }
                        mPayTypes.add(data);
                    }
                    if (mPayTypes.size() == 0) {
                        L.d("支付方式不在本地中");
                        return;
                    }
                    MyApplication.getInstance().setPayTypes(mPayTypes);
                }
            });
        }
    }

}
